<!-- 机构新增-编辑 -->
<template>
  <div class="vue-box submit-box--dialog" style="width: 700px">
    <div class="c-card">
      <el-form :inline="false" label-width="11em" :model="state.model" ref="$form">
        <in-input type="text" prop="fixmedins_name" name="机构名称" v-model="state.model.fixmedins_name" required></in-input>
        <in-input type="text" prop="fixmedins_code" name="机构编码" v-model="state.model.fixmedins_code" required></in-input>
        <div class="df">
          <in-input v-if="!state.id" class="flex1" type="password" prop="pwd" name="登录密码" v-model="state.model.pwd" required :clearable="false">
            <template #suffix v-if="state.id">
              <el-button size="small" text class="copy-btn" :icon="CopyDocument" type="info" @click="sa.copyText(state.model.pwd)">复制</el-button>
            </template>
          </in-input>
          <el-form-item label="登录密码">
            <el-button v-if="state.id" size="small" type="primary" @click="onResetPwd">修改密码</el-button>
          </el-form-item>
        </div>
        <in-input type="password" prop="confirmPwd" name="确认密码" v-model="state.model.confirmPwd" v-if="!state.id" required></in-input>
        <in-input type="text" prop="Director" name="负责人姓名" v-model="state.model.Director" required></in-input>
        <in-input type="text" prop="fixmedins_phone" name="负责人手机号" v-model="state.model.fixmedins_phone" required></in-input>
        <in-input
          type="dictSelect"
          prop="fixmedins_type"
          name="医疗服务机构类型"
          dictName="fixmedins_type"
          v-model="state.model.fixmedins_type"
          required
        ></in-input>
        
        <!-- 新增密钥信息项 -->
        <el-form-item label="接入密钥信息">
          <el-button type="primary" @click="openKeyInfoDialog">配置密钥信息</el-button>
        </el-form-item>
        
        <in-input
          type="img"
          prop="FrontAccessoryId"
          :accessoryUrls="state.model.FrontAccessoryUrl"
          name="法人身份证正面"
          uploadType="43"
          v-model="state.model.FrontAccessoryId"
          :limit="1"
          required
        ></in-input>
        <in-input
          type="img"
          prop="BackAccessoryId"
          :accessoryUrls="state.model.BackAccessoryUrl"
          name="法人身份证反面"
          uploadType="43"
          v-model="state.model.BackAccessoryId"
          :limit="1"
          required
        ></in-input>
        <in-input
          type="img"
          prop="BusinessLicenseAccessoryId"
          :accessoryUrls="state.model.BusinessLicenseAccessoryUrl"
          name="营业执照"
          v-model="state.model.BusinessLicenseAccessoryId"
          :limit="1"
          required
        ></in-input>
        <in-input type="img" prop="DrugBLAccessoryId" :accessoryUrls="state.model.DrugBLAccessoryUrl" name="药品经营许可证" v-model="state.model.DrugBLAccessoryId"></in-input>
        <in-input type="img" prop="MedicalDeviceBLAccessoryId" :accessoryUrls="state.model.MedicalDeviceBLAccessoryUrl" name="医疗器械经营许可证" v-model="state.model.MedicalDeviceBLAccessoryId"></in-input>
        <in-input type="img" prop="GSCertificateAccessoryId" :accessoryUrls="state.model.GSCertificateAccessoryUrl" name="GS认证证书" v-model="state.model.GSCertificateAccessoryId"></in-input>
        <in-input type="img" prop="AccountLicenceAccessoryId" :accessoryUrls="state.model.AccountLicenceAccessoryUrl" name="开户许可证" v-model="state.model.AccountLicenceAccessoryId"></in-input>
      </el-form>
    </div>
    
    <!-- 密钥信息弹窗 -->
    <el-dialog v-model="keyInfoDialogVisible" title="密钥信息配置" width="500px" :before-close="handleKeyInfoClose" append-to-body>
      <el-form :model="keyInfoModel" :rules="keyInfoRules" ref="keyInfoForm" label-width="120px" class="padding">
        <in-input type="text" prop="Secretid" name="密钥ID" v-model="keyInfoModel.Secretid" required></in-input>
        <in-input type="text" prop="SecretKey" name="密钥Key" v-model="keyInfoModel.SecretKey" required></in-input>
        <in-input type="textarea" prop="PrivateKey" name="定点医药机构私钥" v-model="keyInfoModel.PrivateKey" required></in-input>
        <in-input type="textarea" prop="PublicKey" name="医保电子处方中心公钥" v-model="keyInfoModel.PublicKey" required></in-input>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="keyInfoDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveKeyInfo">保存</el-button>
        </span>
      </template>
    </el-dialog>
    
    <resetPwd ref="$resetPwd" @confirm="resetPwdConfirm"></resetPwd>
  </div>
</template>

<script setup name="org-edit">
import { CopyDocument } from '@element-plus/icons-vue'
import { getCurrentInstance, onMounted, ref, reactive } from 'vue'
import resetPwd from '@/components/reset-pwd/reset-pwd.vue'
import md5 from 'md5'
const { proxy } = getCurrentInstance()

const $resetPwd = ref(null)
const $form = ref(null)
const keyInfoForm = ref(null)
// 获取插值
const prop = defineProps({
  param: { type: Object },
})

// ------------------ 数据 ------------------
const state = reactive({
  id: proxy.param.id || 0, // 获取传值id （0=添加，非0=修改）
  model: {
    // 数据 Model
  },
})

// 密钥信息弹窗相关
const keyInfoDialogVisible = ref(false)
const keyInfoModel = reactive({
  Secretid: '',
  SecretKey: '',
  PrivateKey: '',
  PublicKey: ''
})

// 密钥信息表单验证规则
const keyInfoRules = {
  Secretid: [
    { required: true, message: '请输入密钥ID', trigger: 'blur' }
  ],
  SecretKey: [
    { required: true, message: '请输入密钥Key', trigger: 'blur' }
  ],
  PrivateKey: [
    { required: true, message: '请输入定点医药机构私钥', trigger: 'blur' }
  ],
  PublicKey: [
    { required: true, message: '请输入医保电子处方中心公钥', trigger: 'blur' }
  ]
}

// 组件加载时触发
onMounted(function () {
  if (state.id !== 0) {
    const params = {
      MedinsinfoId: state.id,
    }
    sa.ajax('/api/webPresAdmin/medinsinfoDetail?MedinsinfoId=', params, function (res) {
      if (!res.data) {
        return sa.alert('数据不存在')
      }
      state.model = res.data
      
      // 如果有密钥信息，则填充到表单中
      if (res.data.Secretid) {
        keyInfoModel.Secretid = res.data.Secretid
      }
      if (res.data.SecretKey) {
        keyInfoModel.SecretKey = res.data.SecretKey
      }
      if (res.data.PrivateKey) {
        keyInfoModel.PrivateKey = res.data.PrivateKey
      }
      if (res.data.PublicKey) {
        keyInfoModel.PublicKey = res.data.PublicKey
      }
    })
  }
})

// ------------------ 函数 ------------------

// 打开密钥信息弹窗
function openKeyInfoDialog() {
  keyInfoDialogVisible.value = true
}

// 保存密钥信息
function saveKeyInfo() {
  keyInfoForm.value.validate((valid) => {
    if (valid) {
      // 将密钥信息保存到主表单model中
      state.model.Secretid = keyInfoModel.Secretid
      state.model.SecretKey = keyInfoModel.SecretKey
      state.model.PrivateKey = keyInfoModel.PrivateKey
      state.model.PublicKey = keyInfoModel.PublicKey
      
      keyInfoDialogVisible.value = false
      sa.msg('配置成功，点击确定按钮可保存密钥信息')
    }
  })
}

// 关闭密钥信息弹窗前的处理
function handleKeyInfoClose(done) {
  keyInfoForm.value.resetFields()
  done()
}

// 提交表单
defineExpose({
  ok: async function () {
    // 表单校验
    try {
      let res = await $form.value.validate()
      console.log('res ==', res)
      let model = {
        ...state.model,
        // pwd: md5(state.model.pwd).toUpperCase(),
        // MedinsinfoId: state.model.id || '',  
        // 包含密钥信息
        Secretid: keyInfoModel.Secretid,
        SecretKey: keyInfoModel.SecretKey,
        PrivateKey: keyInfoModel.PrivateKey,
        PublicKey: keyInfoModel.PublicKey
      }
      console.log('model', model)
      // 如果是增加
      if (!state.id) {
        sa.ajax('/api/webPresAdmin/addMedinsinfo', model, function (res) {
          sa.alert('添加成功', function () {
            sa.closeModel()
            sa.currView().f5()
          })
        })
      } else {
        // 如果是修改
        sa.ajax('/api/webPresAdmin/editMedinsinfo', model, function (res) {
          sa.alert('修改成功', function () {
            sa.closeModel()
            sa.currView().f5()
          })
        })
      }
    } catch (error) {}
  },
})

// 修改密码
function onResetPwd() {
  $resetPwd.value.open()
}

function resetPwdConfirm(pwd) {
    const params = {
        ...state.model,
        pwd
    }
  sa.ajax('/api/webPresAdmin/editMedinsinfo', params, function (res) {
    sa.alert('修改成功', function () {
     $resetPwd.value.close()
    })
  })
}
</script>
<style></style>